package com.wwdx.aop;

import com.wwdx.model.upms.UpmsLog;
import com.wwdx.service.upms.UpmsLogServiceI;
import com.wwdx.shiro.SessionUser;
import com.wwdx.utils.IpUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 后台管理系统日志记录
 * @author liguoliang
 * @date 2018/2/10 10:40
 */
@Aspect
@Component
public class AdminControllerAop {

	/**
	 * 命名的ThreadLocal指定线程名称
	 */
	private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("AdminStopTime-AdminStartTime");

	/**
	 * 注解里要使用的变量只能是常量类型
	 */
	private static final String POINT = "execution(public * com.wwdx.controller.admin.*.*(..))";
	@Resource
	private UpmsLogServiceI upmsLogService;

	@Before(POINT)
	public void doBeforeInServiceLayer(JoinPoint joinPoint) {
        //1、开始时间
        long beginTime = System.currentTimeMillis();
        //线程绑定变量（该数据只有当前请求的线程可见）
        startTimeThreadLocal.set(beginTime);
	}

	@After(POINT)
	public void doAfterInServiceLayer(JoinPoint joinPoint) {

	}

	@Around(POINT)
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		//获取request
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
		HttpServletRequest request = servletRequestAttributes.getRequest();

		// 从注解中获取操作名称、获取响应结果
		Object result = pjp.proceed();
        //2、结束时间
        long endTime = System.currentTimeMillis();
        //得到线程绑定的局部变量（开始时间）
        long beginTime = startTimeThreadLocal.get();
        String name = SessionUser.getUserName();
        if (StringUtils.isNotBlank(name)){
			UpmsLog upmsLog = UpmsLog.builder()
					.ip(IpUtils.getIpAddr(request)).method(request.getMethod()).spendTime((int) (endTime - beginTime))
					.uri(request.getRequestURI()).username(name).gmt_created(new Date()).build();
            upmsLogService.save(upmsLog);
        }
		return result;
	}
}